package com.sparrow.core;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class ThreadPool {
	public int threadPoolSize = 10;
	public String lock = "runing";
	public Stack<Thread> threadPool = new Stack<Thread>();

	public Map<String, String> resource = new HashMap<String, String>();

	/**
	 * @param args
	 *            2013-7-8下午9:51:00 harry
	 * @throws InterruptedException
	 */
	public static void main(String[] args) throws InterruptedException {
		final ThreadPool threadManage = new ThreadPool();

		for (int i = 0; i < 10000; i++) {
			if (threadManage.threadPool.size() == 10) {
				/*
				 * 1.有synchronized的地方不一定有wait,notify
				 * 
				 * 2.有wait,notify的地方必有synchronized.这是因为wait和notify不是属于线程类，
				 * 而是每一个对象都具有的方法，而且，这两个方法都和对象锁有关，有锁的地方，必有synchronized。
				 * 3.wait对象引用不能被修改 否则会报java.lang.IllegalMonitorStateException
				 * IllegalMonitorStateException - if the current thread is not
				 * the owner of the object's monitor.
				 */
				synchronized (threadManage) {
					// threadManage.lock不被改变则可以wait lock
					threadManage.lock = "wait";
					System.out.println("wait");
					threadManage.wait();
				}
			} else {
				Parameter4Thread pt = new Parameter4Thread();
				pt.setThreadPool(threadManage);
				pt.setResourceKey("1");
				Thread thread = new Thread(pt);
				thread.setDaemon(true);
				thread.start();
				threadManage.threadPool.push(thread);
			}
		}
	}
}

class Parameter4Thread implements Runnable {
	ThreadPool threadPool;

	public ThreadPool getThreadPool() {
		return threadPool;
	}

	public void setThreadPool(ThreadPool threadPool) {
		this.threadPool = threadPool;
	}

	private String resourceKey;

	public String getResourceKey() {
		return resourceKey;
	}

	public void setResourceKey(String resourceKey) {
		this.resourceKey = resourceKey;
	}

	@Override
	public void run() {
		try {
			Thread.sleep(100);
			System.out.println(this.resourceKey);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getId());
		this.getThreadPool().threadPool.remove(Thread.currentThread());
		if (this.getThreadPool().lock.equals("wait")) {
			this.getThreadPool().lock = "runing";
			synchronized (this.getThreadPool()) {
				this.getThreadPool().notify();
				System.out.println("notify");
			}
		}
	}
}
